<template>
    <el-dialog
        :close-on-click-modal="false"
        :show-close="showCloseIcon"
        :visible="searchFlag"
        class="zdy-dialog" width="1000px"
        :title="this.i18n.t('search')"
        :lock-scroll="false"
        :before-close="handleCloseDialog">
        <el-alert
                :title="this.i18n.t('Search for unbound devices in the device management table.')"
                :closable="false"
                show-icon
                type="info">
        </el-alert>
        <br>
        <div class="table-container table-box globalDiv">
<!--          {{percentage}}-->
          <el-progress v-if="searchLoading" :show-text="false" :percentage="percentage"></el-progress>
            <BaseGlobalTable
                    :table_config="table_config"
                    @handleSelectionChange="handleTableSelectionChange"
                    ref="devListTable"
            ></BaseGlobalTable>
            <el-button size="mini" style="margin-left: 10px" v-if="!searchLoading" :loading="searchLoading" @click="deviceinfoStartsearch"
                       icon="el-icon-search" >{{searchStr}}</el-button>
          <el-button type="danger" v-if="searchLoading" size="mini" style="margin-left: 10px" @click="manuallyStopSearch">{{this.i18n.t('stop search')}}</el-button>
            <br>
            <br>
        </div>
        <br>
        <div class="footBtnBox">
            <el-button size="small" type="handle" @click="handleCloseDialog" v-if="showCloseIcon">{{this.i18n.t('Cancel')}}</el-button>
            <el-button size="small" type="primary" @click="submitForm" :loading="saveLoading">{{this.i18n.t('save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {deviceTypeList} from '@/assets/common/js/utils/deviceConfig.js'
    import { sbglGetDeviceid,sbglManualCreate,deviceinfoStartsearch,deviceinfoStopsearch } from '@/api/sbgl'

    import {personnelinfoCleanallperson} from "@/api/pcmj/zzxx";
    //引入接口
    export default {
        name: "searchDevice",
        provide(){
            return {
                // reload: this.reload
            }
        },
      watch:{
        '$store.state.addDeviceList':{
          handler (newVal,oldVal) {
            //对数据执行操作
            console.log('设备列表变化了',newVal,oldVal)
            this.table_config.table_tbody=newVal
            console.log('表格数据',this.table_config.table_tbody);
            this.$nextTick(()=>{
              this.$refs.devListTable.loading_data()
            })

          },
          deep: true // 深度监听
        },
        '$store.state.addDeviceListLoading':{
          handler (newVal,oldVal) {
            // debugger
            // console.log(60,newVal);
            //对数据执行操作
            this.searchLoading=newVal

            if (newVal==false){
              this.searchStr=this.i18n.t('search')
            }
            console.log('addDeviceListLoading变化了',newVal);
          },
          deep: true // 深度监听
        },
      },
      beforeDestroy() {
          // 离开页面时，清空store内的设备列表数据
        this.$store.commit('resetAddDeviceList',[])
        // 停止搜索设备
        this.deviceinfoStopsearch()
      },
      data(){
            return{
              showCloseIcon:true,
              percentage:0,
                saveLoading:false,
                devOptions:null,
                searchStr:this.i18n.t('In search...'),//搜索中...
                searchLoading:true,
                // 数据分析
                table_config: {
                  rowClassName:( row,rowIndex)=>{
                    console.log(97,row, rowIndex);
                  },
                    table_tbody: [
                    ],
                    thead: [
                        // 序列号
                        {label: this.i18n.t('Serial number'),width:"150", prop: "deviceCode",type: "function",callback:(row)=>{
                                return row.deviceCode
                            }},
                        // 设备类型
                        {label: this.i18n.t('Device type'),width:"100", prop: "deviceType",type:'function',callback:(row)=>{
                          if (row.deviceType===-1){
                            // 未知
                            return this.i18n.t('unknown')
                          }else{
                            return this.i18n.t(deviceTypeList[row.deviceType].label)
                          }

                            }},
                        // 设备名称
                        {label: this.i18n.t('Device name'), prop: "deviceName",type:'function',callback:function (row){
                                return row.deviceName||'-'
                            }},
                        {label: "IP", prop: "ip",width:"170",type: "function",callback:(row)=>{
                                return row.ip
                            }},
                        // 端口
                        {label:this.i18n.t('port'), prop: "port",type:'function',callback:function (row){
                                return row.port||'-'
                            }},
                      // 是否可用
                      {label: this.i18n.t('Availability or not'), prop: "available",width:"100",type:'function',callback: (row)=>  {
                          return row.available?
                              // 可用
                              "<span style='color: #2e8245'>"+this.i18n.t('usable')+"</span>"
                              :
                              // 不可用
                              "<span style='color: red'>"+ this.i18n.t('Not available')+"</span>"

                        }},
                      // 是否绑定
                      {label: this.i18n.t('Bind or not'), prop: "isBindding",width:"150",type:'function',callback: (row)=> {
                        if (row.available){
                          var isBindding= row.isBindding*1

                          if (isBindding===0){
                            // 未绑定
                            return this.i18n.t('Not yet bound')
                          }
                          if (isBindding===1){
                            // 已绑定
                            return this.i18n.t('Bound')
                          }
                          if (isBindding===2){
                            // 未知
                            return this.i18n.t('unknown')
                          }
                        }else{
                          //未知
                          return this.i18n.t('unknown')
                        }

                        }},
                      // MAC地址
                      {label: this.i18n.t('MAC address'),width:"200", prop: "mac",type:'function',callback:function (row) {
                          return row.mac||'-'
                        }},
                    ],
                    tableButtonArr: [
                        // {
                        //     iconClass: "el-icon-search",
                        //     btnType: 2,
                        //     text: "搜索",
                        //     callback: "searchDevice",
                        //     power: "search",
                        //     customIcon:true
                        // }
                    ],
                    // 列表前面是否需要显示 checkbox 框，如要显示 值写成 true
                    checkbox: true,
                    height:300,
                    index: true,
                    showPagination: false, // 翻页器
                    // 请求表格数据的 url ，可直接传入
                    // url: 'deviceinfo/searchdevices?_time='+new Date().getTime(),
                    // 请求表格数据的 方式
                    // method: "get",
                    //表格 title 文字
                    tableTitle: false,
                    //是否需要给 th 加 样式boder 如果需要加上addBoderClass 不需要显示空或者不加这个字段配置
                    addBoderClass: "addBoderClass",
                    roleList: [],
                },
                form:{
                },
                selectRow: [],
                isRouterAlive:true
            }
        },
        props: {
            searchFlag: {
                type: Boolean,
                default: false
            }
        },
        methods:{
          updateProgress(){
            var totalTime = 30000; // 30秒
            var interval = 1000; // 更新间隔
            var updateInterval=setInterval(()=>{
              this.percentage+=100/60
              if (this.percentage>=100){
                this.percentage=100
                clearInterval(updateInterval)
              }
            },1000)
          },
            // 刷新
            reload(){
                // this.isRouterAlive=false
                // this.$nextTick(()=>this.isRouterAlive=true)
            },
            // 刷新列表
            parentUpdate(){
                this.$emit("update:searchFlag",false);
                this.$parent.$refs.globalTable.loading_data();
            },
            // 手动添加
            sbglManualCreate(params, num){
                 // 隐藏关闭按钮
                this.showCloseIcon=false
                this.saveLoading=true
                sbglManualCreate(params).then((res) => {
                    if (res.code === 200) {
                        // 添加成功!
                        this.W.$tips("success", this.i18n.t('Add successfully!'));
                        if (num == 1) {

                        }
                        this.parentUpdate();
                    }
                }).catch().finally(() => {
                  // 恢复关闭弹窗按钮显示
                    this.showCloseIcon=true
                  // 关闭按钮loading状态
                    this.saveLoading=false
                })
            },
            // 监控勾选操作
            handleTableSelectionChange(selection){
                console.log(selection);
                this.selectRow = selection;
            },
            // 关闭弹框
            handleCloseDialog(){
                this.$emit('update:searchFlag', false);
            },
            // 保存方法
            submitForm() {
                if(!this.selectRow.length){
                    // 请在表格内勾选要添加的设备
                    this.W.$tips("warning", this.i18n.t('Please check the device you want to add in the form!'));
                }else{
                    // 确定要添加选择的设备吗
                    this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to add the selected device?'))
                        .then(async () => {
                            var idItem=[]
                            // var _this = this;
                            this.selectRow.forEach(item=>{
                                let params={
                                    deviceName:item.deviceName,
                                    deviceType:item.deviceType,
                                    ip:item.ip,
                                    deviceCode:item.deviceCode
                                }
                                idItem.push(params);
                            })
                            console.log(idItem);
                            for (const i in idItem) {
                                this.sbglManualCreate(idItem[i], i+1==idItem.length ? 1 : 0)
                            }
                        })
                        .catch(() => {

                        });
                }
            },
          // 手动停止搜索设备
          manuallyStopSearch(){
            this.selectRow=[]
            // 停止搜索设备
            this.deviceinfoStopsearch()
            this.$store.commit('setAddDeviceListLoading',false)
            this.percentage=100

          },
          // 停止搜索设备
          deviceinfoStopsearch(){
            deviceinfoStopsearch().then(res => {
              if (res.code == 200) {

                // this.$refs.globalTable.loading_data()
              }
            }).catch().finally(()=>{

            })
          },
          // 开始搜索设备
          deviceinfoStartsearch(){
            this.$store.commit('setAddDeviceListLoading',true)
            this.percentage=0
            // 搜索中...
            this.searchStr=this.i18n.t('In search...')
            // 停止搜索设备
            // this.deviceinfoStopsearch()
            // 离开页面时，清空store内的设备列表数据
            this.$store.commit('resetAddDeviceList',[])
            deviceinfoStartsearch().then(res => {
              if (res.code == 200) {
                this.updateProgress()
                // this.$refs.globalTable.loading_data()
              }
            }).catch().finally(()=>{

            })
          }
        },
        mounted(){

            this.devOptions=deviceTypeList
            console.log(190,this.devOptions);
            this.deviceinfoStartsearch()
            // this.$nextTick(async () => {
            //     this.$refs.devListTable.loading_data(this.form)
            // });
        }
    }
</script>

<style scoped>

</style>
